package com.lsy.controller.front;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.lsy.entity.FlowRecordType;
import com.lsy.entity.Flowrecord;
import com.lsy.entity.Invest;
import com.lsy.entity.ProductCustom;
import com.lsy.entity.User;
import com.lsy.service.interf.FlowRecordService;
import com.lsy.service.interf.InterestService;
import com.lsy.service.interf.InvestService;
import com.lsy.service.interf.ProductService;
import com.lsy.service.interf.UserService;
import com.lsy.util.DateUtil;

@Controller
@RequestMapping("/front/product")
@SessionAttributes({ "user" })
public class ProductFrontController {

	private final int EXPIRE = 1;

	@Autowired
	private ProductService productService;

	@Autowired
	private InvestService investService;

	@Autowired
	private UserService userService;

	@Autowired
	private FlowRecordService flowRecordService;

	@Autowired
	private InterestService interestService;

	@RequestMapping
	public ModelAndView index() {
		ModelAndView view = new ModelAndView("/FrontEnd/products");
		view.addObject("pageNumber", productService.getPageNumber());
		return view;
	}

	//查询
	@RequestMapping("/query")
	@ResponseBody
	public Map<String, Object> query(int page) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", "fail");
		try {
			int total = productService.findTotal();
			List<ProductCustom> products = productService.findProductByPage(page, total);
			result.put("total", total);
			result.put("products", products);
			result.put("code", "success");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping("/detail")
	public ModelAndView detail(int id) {
		ModelAndView view = new ModelAndView("/FrontEnd/detail");
		try {
			double temp = 0;
			String schedule = null;
			ProductCustom product = productService.findProductById(id);
			if (product == null) {
				product = new ProductCustom();
			} else {
				DecimalFormat format = new DecimalFormat(".0");
				temp = (double)(product.getPpricecurrent()) / (double)(product.getPpricetotal());
				schedule = format.format(temp * 100);
				// 满额
				if (product.getPpricecurrent().equals(product.getPpricetotal())) {
					switch (product.getPtype()) {
					case EXPIRE:
						product.setPdonetime(
								DateUtil.getNumberNext(product.getPdonetime(), product.getPtimelimit()).getTime());
						break;
					default:
						Date date = null;
						if (DateUtil.isLastDayOfMonth(product.getPdonetime())) {
							date = DateUtil.getLastDayOfMonth().getTime();
						} else {
							int doneDay = DateUtil.getDay(product.getPdonetime());
							int today = DateUtil.getDay();
							Calendar calendar = Calendar.getInstance();
							calendar.setTime(product.getPdonetime());
							if (today <= doneDay) {
								calendar.set(Calendar.MONTH, DateUtil.getMonth());
							} else {
								calendar.set(Calendar.MONTH, DateUtil.getMonth() + 1);
							}
							date = calendar.getTime();
						}
						product.setPdonetime(date);
						break;
					}
				}
			}
			view.addObject("product", product);
			view.addObject("schedule", schedule);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return view;
	}

	//投资功能
	@RequestMapping(path = "/buy", method = RequestMethod.POST)
	@ResponseBody
	public String buy(int money, int productId, @ModelAttribute("user") User user) {
		String result = "{\"code\":\"fail\"}";
		try {
			//获取散标
			ProductCustom product = productService.findProductById(productId);
			//获取用户余额
			long userMoney = userService.findUserMoney(user.getUserid());
			if (product.getPpricetotal() >= (product.getPpricecurrent() + money) && userMoney > money) {
				//新建投资记录
				Invest invest = new Invest();
				invest.setIinvesttime(new Date());
				invest.setIlendmoney(money);
				invest.setProductid(productId);
				invest.setUserid(user.getUserid());
				if (investService.save(invest)) {
					userMoney = userMoney - money;
					if (userService.updateMoney(userMoney, user.getUserid())) {
						user.setUmoney(userMoney);
						long currentPrice = product.getPpricecurrent() + money;
						boolean isComplete = false;
						//判断散标是否满额
						if (currentPrice == product.getPpricetotal()) {
							product.setPdonetime(new Date());
							product.setPisdone(true);
							isComplete = true;
						}
						product.setPpricecurrent(currentPrice);
						product.setPpeoplecurrent(product.getPpeoplecurrent() + 1);
						if (productService.updateProduct(product, isComplete)) {

							// 添加流水记录
							Flowrecord record = new Flowrecord();
							record.setProductid(product.getProductid());
							record.setFmoneyleft((int) userMoney);
							record.setUserid(user.getUserid());
							record.setFmoneydeal(money);
							record.setFtimedeal(new Date());
							record.setFtypedeal(FlowRecordType.BUY_PRODUCT.getType());
							if (isComplete == true) {
								int number = interestService.createInterestByProduct(product);
								System.out.println("散标满额，共创建 " + number + " 条利息信息。");
							}
							flowRecordService.save(record);

							result = "{\"code\":\"success\"}";
						} else { // 修改信息失败，将刚刚的投标一并删除
							investService.deleteById(invest.getInvestid());
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
